import json

from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumer
import time
import random

agvUser_list = set()


class ChatConsumer(WebsocketConsumer):
    def websocket_connect(self, message):
        # print("websocket连接已建立")
        self.accept()
        # self.send("欢迎来到我的站点！！！")
        agvUser_list.add(self)

    def websocket_receive(self, message):
        info = message['text']
        if info == '我来了':
            # 向前端传递监控数据（angur,linear....）
            data = dict(
                linearSpeed=random.randint(0, 20),
                angularSpeed=random.random()
            )
            print("发送给前端的数据：", json.dumps(data))
            for agvUser in agvUser_list:
                agvUser.send(json.dumps(data))  # data数据需要序列化

    def websocket_disconnect(self, message):
        raise StopConsumer()
